# _*_ encoding: utf-8 _*_

import optparse
from generate_od import generate_gauss_distribution
from generate_od import load_routes
from generate_od import load_vtypes
from assgin_vehicles import assign_vtype
import os
import math
import random

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


def get_options(args=None):
    optparser = optparse.OptionParser()
    optparser.add_option("-r", "--route-directory", dest="route_dir", help="The route file seed directory")
    optparser.add_option("-v", "--vtypes", dest="vtypes_file", help="The vehicle type file")
    optparser.add_option("-o", "--output", dest="output_file", help="the output route file")
    optparser.add_option("-n", "--number", dest="number", type="int", help="an integer describes the vehicle amounts")
    optparser.add_option("--time-avg", dest="tavg", type='float', help="an float number describes the average value of depart time ")
    optparser.add_option("--time-std", dest="tstd", type="float", help="an float number describes the standard derivation of depart time")

    (options, args) = optparser.parse_args(args=args)
    if not options.route_dir or not options.vtypes_file or not options.number or not options.tavg or not options.tstd:
        optparser.print_help()
        exit(0)
    return options


def generate_routes(seed_routes, output, vtypes, t_samles):
    # root = ET.ElementTree('routes')
    # root.attrib['xmlns:xsi'] = "http://www.w3.org/2001/XMLSchema-instance"
    # root.attrib['xsi:noNamespaceSchemaLocation'] = "http://sumo.dlr.de/xsd/routes_file.xsd"
    # seed_len = len(seed_routes)
    # for id, depart in enumerate(t_samles):
    #     index = random.randint(0, seed_len - 1)
    #     subnode = ET.SubElement(root, "vehicle")
    #     attrib = {}
    #     attrib.setdefault('id', "{0}".format(id))
    #     attrib.setdefault('depart', "{0}".format(depart))
    #     attrib.setdefault('departLane', "best")
    #     attrib.setdefault('departSpeed', "0.00")
    #     attrib.setdefault('departPos', "base")
    #     attrib.setdefault("arrivalPos", "random")
    #     attrib.setdefault('type', assign_vtype(vtypes))
    #     subnode.attrib = attrib
    #     route_node = ET.SubElement(subnode, "route")
    #     route_node.attrib.setdefault('edges', " ".join(seed_routes[index]))
    # write_format_xml(ET.tostring(root, "utf-8"), output)
    with open(output, "wb") as f:
        f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        f.write('<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/routes_file.xsd">\n')
        seed_len = len(seed_routes)
        for id, depart in enumerate(t_samles):
            index = random.randint(0, seed_len - 1)
            line = '\t<vehicle arrivalPos="random" depart="{0}" departLane="best" departPos="base" departSpeed="0.00" id="{1}" type="{2}">\n'.format(depart, id, assign_vtype(vtypes))
            f.write(line)
            f.write('\t\t<route edges="{0}"/>\n'.format(" ".join(seed_routes[index])))
            f.write('\t</vehicle>\n')
        f.write('</routes>')


def main(options=None):
    route_dirs = os.walk(options.route_dir)
    route_files = []
    for root, dirs, files in route_dirs:
        for f in files:
            if f.endswith(".rou.xml"):
                route_files.append(os.path.join(root, f))

    routes = load_routes(route_files)
    vtypes = load_vtypes(options.vtypes_file)

    samples = generate_gauss_distribution(avg=options.tavg, std=options.tstd, n=options.number)
    samples.sort()
    for i, t in enumerate(samples):
        samples[i] = int(math.floor(t))

    generate_routes(routes, options.output_file, vtypes, samples)

if __name__ == '__main__':
    main(get_options())